package com.platform.data.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.platform.data.common.CommonConstant;
import com.platform.data.handle.ExcelDataListener;
import com.platform.data.model.ReadDataModel;
import com.platform.data.service.ReadAndWriteExcelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 读取Excel文件业务接口
 *
 * @author weijun.zhu
 * @date 2025/5/10 13:16
 */
public class ReadAndWriteExcelServiceImpl implements ReadAndWriteExcelService {
    private static final Logger log = LoggerFactory.getLogger(ReadAndWriteExcelServiceImpl.class);
    /**
     * 默认读取文件Sheet数量
     */
    private static final Integer DEFAULT_SHEET_NUM = 3;
    /**
     * 读取文件内容
     *
     * @param filePath filePath
     * @return {@link List<ReadDataModel>}
     */
    @Override
    public List<ReadDataModel> read(String filePath) {
        log.info("ReadExcelServiceImpl.read|开始解析Excel文件，文件路径：{}", filePath);
        List<ReadDataModel> dataList = new ArrayList<>();

        ExcelReader reader = EasyExcelFactory.read(filePath).build();
        List<ReadSheet> sheetList = new ArrayList<>();
        for (int i = 0; i < DEFAULT_SHEET_NUM; i++) {
            ReadDataModel readData = new ReadDataModel(i == CommonConstant.ZERO);
            ReadSheet sheet = EasyExcelFactory.readSheet(i)
                    .registerReadListener(new ExcelDataListener(readData))
                    .build();
            sheetList.add(sheet);
            dataList.add(readData);
        }
        reader.read(sheetList);
        reader.finish();
        log.info("ReadExcelServiceImpl.read|结束解析Excel文件，文件路径：{}", filePath);
        return dataList;
    }
}
